goog.provide('mitel.contextual_gadget');

goog.require('goog.async.Delay');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.style');
goog.require('goog.Timer');
goog.require('mitel.contextual_gadget.widget');
goog.require('mitel.contacts');
goog.require('mitel.deployment');
goog.require('mitel.messaging');
goog.require('mitel.socket');

/**
 * @type {object} The socket to the backend server for this gadget
 */
mitel.contextual_gadget.socket;

/**
 * @type {string} Holds the name or email address of the sender
 */
mitel.contextual_gadget.sender_name="";
mitel.contextual_gadget.sender_email="";

mitel.contextual_gadget.contactsCallback = function(res)
{
   if (res == true)
   {
      // Got contacts info. Get the name of the sender
      mitel.contextual_gadget.sender_name = mitel.contacts.get_name_from_email(mitel.contextual_gadget.sender_email);
      if("Name not given" == mitel.contextual_gadget.sender_name)
      {
          mitel.contextual_gadget.sender_name = "sender"
      }
      goog.dom.setTextContent(sender_name, mitel.contextual_gadget.sender_name);
   }
   else
   {
      // Did not get any contacts info
      alert("Did not get contacts");
   } 
}

/**
 * The main entry point of the gadget. Triggered once proper authorization to
 * access User's email address has been granted.
 *
 * @param {string} emailAddress Email address of logged in user.
 */
var main = function(emailAddress) {
  goog.style.setStyle(auth, 'display', 'none');

  var matches = google.contentmatch.getContentMatches();

  var sender_addr="sender";
  var message_id;

  for (var match in matches) {
    for (var key in matches[match]) {
      if (key == 'message_id') {
        message_id = matches[match][key];
      }
      if (key == 'sender_email') {
        mitel.contextual_gadget.sender_email = matches[match][key];
      }
    }
  }

  // Fetch contacts data. This is an asynchronous call so
  // you may not have the data after the function returns.
  mitel.contacts.fetchContactsData(mitel.contextual_gadget.contactsCallback);

  var away_from_desk = false;
  
  var call = goog.dom.getElement('call_person');
  goog.events.listen(call, goog.events.EventType.CLICK,
      function(e)
      {
          e.preventDefault();
          mitel.contextual_gadget.socket.emit('call', {
              'message_id': message_id,
              'isMobile': mitel.messaging.getMobile() || away_from_desk
          });
      });
  mitel.contextual_gadget.socket = mitel.socket.connect(mitel.deployment.socket_server);
  
  mitel.contextual_gadget.socket.on('connect', function() {
    mitel.contextual_gadget.socket.emit('nickname', {
      'nickname': emailAddress
    });
    // Once connected, stop the spinner 
    goog.style.showElement(context_spinner, false);
  });

  var mobile_indicator = goog.dom.getElement('context_mobile_indicator');
  var will_call_desk;
  
  var _redrawMobileIndicator = function() {
     var isMobileDevice = mitel.messaging.getMobile();
     
     var from = 'desk';
     var to = 'desk';
     
     var new_will_call_desk;
     
     if (away_from_desk || isMobileDevice) {
        from = 'mobile';
        new_will_call_desk = false;
     } else {
        from = 'desk';
        new_will_call_desk = true;
     }
     
     if (new_will_call_desk == will_call_desk) {
        return;
     }
     will_call_desk = new_will_call_desk;
     
     var indicator = ' from your ' + from + ' phone';
     goog.dom.setTextContent(from_phone, indicator);
     goog.dom.removeChildren(mobile_indicator);
     /*
     soy.renderElement(mobile_indicator, mitel.contextual_gadget.widget.device_indicator, {
        host: mitel.deployment.host,
        from: from,
        to: to
     })
     */ 
  }
  
  mitel.contextual_gadget.socket.on('is_mobile', function(data) {
     away_from_desk = data['isMobile'];
     _redrawMobileIndicator();
  });

  var channel = mitel.messaging.init();
  
  channel.registerService('cookie:sentMobile', function(isMobile) {
     mitel.messaging.recieveMobile(isMobile);
     _redrawMobileIndicator();
  });
  
  var mobileStatusUpdateTimer = new goog.Timer(75);
  mobileStatusUpdateTimer.start();
  goog.events.listen(mobileStatusUpdateTimer, goog.Timer.TICK, function() {
     mitel.messaging.requestMobile();
  });

  // Adjust the height of the gadget
  gadgets.window.adjustHeight(55);
};


/**
 * Show the authorization button. The user should click the button which will
 * trigger the OAuth popup to appear.
 *
 * @param {Object} response The (rejected) response to an API call.
 */
var showAuth = function(response) {
  var popup = new gadgets.oauth.Popup(response.oauthApprovalUrl,
      'height=500,width=500', function() {

      }, function() {
        boot();
      });

  var auth = goog.dom.getElement('auth');
  var auth_button = goog.dom.getElement('auth_button');

  goog.events.listen(
      auth_button,
      goog.events.EventType.CLICK,
      popup.createOpenerOnClick()
  );

  goog.style.setStyle(auth, 'display', 'block');
};


/**
 * Initial gadget boot. We'll setup the main gadget container and attempt to
 * fetch the User's email address via the UserInfo API.
 */
var boot = function() {
  goog.dom.removeChildren(document.body);
  soy.renderElement(document.body, mitel.contextual_gadget.widget.container);

  var JSON = gadgets.io.ContentType.JSON;
  var OAUTH = gadgets.io.AuthorizationType.OAUTH;

  var params = {};
  url = 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json';
  params[gadgets.io.RequestParameters.CONTENT_TYPE] = JSON;
  params[gadgets.io.RequestParameters.AUTHORIZATION] = OAUTH;
  params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = 'google';
  params[gadgets.io.RequestParameters.OAUTH_USE_TOKEN] = 'always';
  params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;

  gadgets.io.makeRequest(url, function(response) {
    if (response.oauthApprovalUrl) {
      showAuth(response);
    } else {
      main(response.data['email']);
    }
  }, params);
};

gadgets.util.registerOnLoadHandler(boot);

